package com.fjec.common.aliyun.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fjec.common.Const;
import com.fjec.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Objects;

@Slf4j
public class AliyunSmsHelper {

    private static final String SYS_DOMAIN = "dysmsapi.aliyuncs.com";

    private static final String SYS_VERSION = "2017-05-25";

    private DefaultProfile profile;

    private IAcsClient client;

    public AliyunSmsHelper(AliSmsConfig config) {
        this.profile = DefaultProfile.getProfile(config.getRegionId(),
                config.getAccessKeyId(), config.getSecret());
        this.client = new DefaultAcsClient(profile);
    }

    public Map<String, Object> sendSms(String regionId, String phoneNumbers, String signName, String tempCode,
                          Map<String, String> param) throws Exception {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(SYS_DOMAIN);
        request.setSysVersion(SYS_VERSION);
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", tempCode);
        request.putQueryParameter("TemplateParam", JsonUtil.toJson(param));
        CommonResponse response = client.getCommonResponse(request);
        String returnStr = response.getData();
        Map<String, Object> returnMap = JsonUtil.jsonToMap(returnStr);
//        if (!Objects.equals("OK", MapUtils.getString(returnMap, "Code"))) {
//            MDC.put(Const.TRACE_ID_KEY, "ERR_SMS");
//            log.error(String.format("[ALI_SMS][ERR]:%s", returnStr));
//            MDC.remove(Const.TRACE_ID_KEY);
//        }
        return returnMap;
    }

    public Map<String, Object> sendSms(String phoneNumbers, String signName, String tempCode,
                          Map<String, String> param) throws Exception {
        return sendSms(profile.getRegionId(), phoneNumbers, signName, tempCode, param);
    }

}
